package 剑指offer;

import java.util.LinkedList;
import java.util.Queue;

public class _37序列化二叉树 {
    public String serialize(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append('[');
        queue.add(root);
        while (!queue.isEmpty()){
            TreeNode poll = queue.poll();
            if(poll != null){
                stringBuilder.append(poll.val).append(",");
                queue.add(poll.left);
                queue.add(poll.right);
            }else{
                stringBuilder.append("null").append(",");
            }
        }
        stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        stringBuilder.append(']');
        return stringBuilder.toString();
    }


    public TreeNode deserialize(String data) {
        String substring = data.substring(1, data.length() - 1);
        String[] split = substring.split(",");
        TreeNode root = new TreeNode(Integer.parseInt(split[0]));
        Queue<TreeNode> queue  = new LinkedList<>();
        queue.add(root);
        int i = 1;
        while (!queue.isEmpty()){
            TreeNode poll = queue.poll();
            if(!split[i].equals("null")){
                poll.left = new TreeNode(Integer.parseInt(split[i]));
                queue.add(poll.left);
            }
            i++;
            if(!split[i].equals("null")){
                poll.right = new TreeNode(Integer.parseInt(split[i]));
                queue.add(poll.right);
            }
            i++;
        }
        return root;
    }
}
